import { defineStore } from 'pinia'
import { ref } from 'vue'
import { doLoginAPI, weixinLoginAPI } from '@/api/user/index'
import type { loginDataType, reqLoginType, responseLoginDataType, responseWeixinLoginDataType } from '@/api/user/type'
export const useUserStore = defineStore(
  'user',
  () => {
    // 控制登录对话框显示与隐藏
    const visiable = ref<boolean>(false)
    // 手机登录用户信息
    const userInfo = ref({} as loginDataType)

    /** 打开登录对话框 */
    const showLogin = () => {
      visiable.value = true
    }
    /** 用户登录
     *
     * @param data {reqLoginType} 用户参数信息
     */
    const doLogin = async (data: reqLoginType) => {
      const { data: res }: responseLoginDataType = await doLoginAPI(data)
      if (res.code !== 200) return ElMessage.error(res.message)
      ElMessage.success('登录成功')
      userInfo.value = res.data
      visiable.value = false
    }
    /** 退出登录 */
    const outLogin = () => {
      userInfo.value.name = ''
      userInfo.value.token = ''
      ElMessage.info('用户已退出登录')
    }
    /** 微信登录
     *
     * @param url {string} 重定向路径
     */
    const weixinLogin = async (url: string, id: string) => {
      const { data: res }: responseWeixinLoginDataType = await weixinLoginAPI(url)
      if (res.code !== 200) return ElMessage.error(res.message)
      const { appid, scope, redirectUri, state } = res.data
      // 生成微信扫码登录二维码登录页面 相关链接（https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html）
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      //@ts-expect-error
      new WxLogin({
        self_redirect: true,
        id: id,
        appid: appid,
        scope: scope, // 当前微信扫码页面已经授权
        redirect_uri: redirectUri, // 填写授权回调路径
        state: state,
        style: 'black',
        href: '',
      })
    }
    /** 微信登录返回用户信息保存 */
    const setwxLoginInfo = (query: loginDataType) => {
      userInfo.value.name = query.name
      userInfo.value.token = query.token
      visiable.value = false
    }

    return {
      visiable,
      showLogin,
      userInfo,
      doLogin,
      outLogin,
      weixinLogin,
      setwxLoginInfo,
    }
  },
  {
    persist: {
      paths: ['userInfo'],
    },
  },
)
